<template>
    <BPTable ref='tableRef' align='center' row-key='id' name-key='name' :columns='columns' :api='pageApi' :buttons='buttons'>
        <template #enable='{record}'>
            <a-tag v-if='record.enable' color='#87d068'>{{$t('enable')}}</a-tag>
            <a-tag v-else>{{$t('disable')}}</a-tag>
        </template>
        
        <!-- <template #$action='{record}'>
            <XTextButton type='primary' :before='getDeptOptionsList' @click='openSetScope(record)'>数据权限</XTextButton>
            <XTextButton type='primary' :before='async () => getMenusOptionsList(record.id)' @click='openSetMenu(record)'>菜单权限</XTextButton>
        </template> -->
    </BPTable>

    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close='close'>
        <a-form ref='formRef' :label-col='{span : 5}' :rules='rules' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item :label='$t("name")' name='name'>
                <a-input type='text' :maxlength='30' show-count v-model:value='formData.name' />
            </a-form-item>
            <a-form-item :label='$t("sort")' name='sort'>
                <a-input type='number' v-model:value.number='formData.sort' />
            </a-form-item>
            <a-form-item :label='$t("menu")' name='menus'>
                <a-tree checkable @check='selectMenus' :selectable='false' v-model:checkedKeys='checkedKeys' :checkStrictly='checkStrictly' :field-names='{children:"children",title:"name",key:"id"}' :tree-data='menuData'></a-tree>
            </a-form-item>
            <a-form-item :label='$t("enable")' name='enable'>
                <a-switch v-model:checked='formData.enable' :checked-children='$t("enable")' :un-checked-children='$t("disable")'/>
            </a-form-item>
            <a-form-item :label='$t("remark")' name='remark'>
                <a-textarea :maxlength='100' show-count v-model:value='formData.remark' />
            </a-form-item>
        </a-form>
    </BDialog>
</template>

<script lang='ts' setup>
    import { permissionMenusApi } from "@/api/system/Menu"
    import { saveApi, pageApi, deleteApi } from "@/api/system/Role"
    import { useI18nStore } from "@/store/i18n"
import { useResourceStore } from "@/store/resource"
    import { recursionFn } from "@/utils"
    import { message, Modal } from "ant-design-vue"
    import { nextTick, ref } from "vue"

    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const tableRef = ref()
    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref<string>()

    let menuRawData:any[] = []
    const menuData = ref<any[]>([])
    const checkedKeys = ref()
    const checkStrictly = ref(true)

    const buttons = ref<SearchButton[]>([])

    if(resourceStore.hasPermission('system:role:add')) {
        buttons.value.push({
            button : 'add',
            func : () => {
                dialogTitle.value = i18n.t('add')
                checkedKeys.value = null
                visible.value = true
            }
        })
    }

    const columns = ref<Column[]>([
        {
            title : i18n.t('name'),
            dataIndex : 'name',
            align : 'center',
            inSearch : true,
        },

        {
            title : i18n.t('sort'),
            dataIndex : 'sort',
            align : 'center',
        },

        {
            title : i18n.t('enable'),
            dataIndex : 'enable',
            align : 'center',
        },
        
        {
            title : i18n.t('remark'),
            dataIndex : 'remark',
            align : 'center',
        },

        {
            title : i18n.t('operation'),
            dataIndex : '$action',
            align : 'center',
            width : '300px',
            $edit : resourceStore.hasPermission('system:role:edit') ? (row) => {
                dialogTitle.value = i18n.t('edit')
                visible.value = true
                nextTick(() => {
                    for(let k in formData.value) {
                        formData.value[k] = row[k]
                    }

                    if(row.menus && row.menus.length > 0) {
                        checkedKeys.value = row.menus
                    }
                })
            } : undefined,

            $delete : resourceStore.hasPermission('system:role:edit') ? async(row) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    tableRef.value.load()
                    message.success(i18n.t('deleteSuccess'))
                }else {
                    message.error(res.msg)
                }
            } : undefined
        }
    ])

    const formData = ref({
        id : 0,
        name : null,
        enable : true,
        sort : 0,
        menus : [],
        remark : ''
    })

    const rules = {
        name : [
            {
                required : true,
                message : i18n.concat('please', 'input', 'name')
            }
        ],
    }

    function queryChild(source:any[], target:number[], parentId:number) {
        source.forEach(item => {
            if(item.parentId == parentId) {
                target.push(item.id)
                queryChild(source, target, item.id)
            }
        })
    }

    function selectMenus(a, { checked, node}) {
        
        let children:number[] = []
        queryChild(menuRawData, children, node.id)

        if(children.length > 0) {
            let selectedKey:number[] = a.checked
            if(checked) { //选中的
                children.forEach(child => {
                    if(selectedKey.includes(child) == false) {
                        selectedKey.push(child)
                    }
                })
            }else { //取消的
                children.forEach(child => {
                    let index = selectedKey.findIndex(k => child == k)
                    if(index >= 0) {
                        selectedKey.splice(index, 1)
                    }
                })
            }

            formData.value.menus = selectedKey
            checkedKeys.value = selectedKey
        }else {
            formData.value.menus = a.checked
        }


        
    }

    function close() {
        formRef.value.resetFields()
        formRef.value.clearValidate()
    }

    async function submit() {
        let params  = await formRef.value.validate()
        
        const res = await saveApi(params)
        if(res.success) {
            tableRef.value.load()
            message.success(i18n.t('saveSuccess'))
            close()
            visible.value = false
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }


    permissionMenusApi().then(res => {
        if(res.data.length > 0) {
            res.data.forEach(row => {
                row.name = i18n.t(row.name)
            })
            menuRawData = res.data
            menuData.value = recursionFn(res.data, Math.min(...res.data.map(row => row.parentId)), 'id', 'parentId', 'children')
        }
        
    })



</script>